package com.dragon.Handler.custom;

import com.alibaba.fastjson.JSON;
import com.dragon.pojo.Problem.JudgeInfo;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@MappedJdbcTypes(JdbcType.VARCHAR)
public class JudgeInfoListTypeHandler extends BaseTypeHandler<List<JudgeInfo>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<JudgeInfo> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public List<JudgeInfo> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseStringToList(rs.getString(columnName));
    }

    @Override
    public List<JudgeInfo> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseStringToList(rs.getString(columnIndex));
    }

    @Override
    public List<JudgeInfo> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseStringToList(cs.getString(columnIndex));
    }

    private List<JudgeInfo> parseStringToList(String dbData) {
        if(dbData == null || dbData.trim().isEmpty()){
            return null;
        }
        return JSON.parseArray(dbData, JudgeInfo.class);
    }
}
